﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;

namespace _5_序列化与反序列化
{
    class Program
    {
        static void Main(string[] args)
        {
            //序列化：将对象转化成二进制
            //反序列化：将二进制转化为对象
            //用途：传输数据(文件流)

            //序列化步骤
            //  1 将这个类标记为可以被序列化的,在要序列化的类上方添加Serializable
            //Person p = new Person();
            //p.Name = "鹿菌";
            //p.Age = 25;
            //p.Gender = '男';
            //using (FileStream fsWrite=new FileStream(@"F:\new2.txt",FileMode.OpenOrCreate,FileAccess.Write))
            //{
            //    //开始序列化对象
            //    BinaryFormatter bf = new BinaryFormatter();
            //    bf.Serialize(fsWrite, p);
            //}
            //Console.WriteLine("序列化成功");
            //  2 接收对方发送过来的二进制，反序列化成对象
            Person p;
            using (FileStream fsRead=new FileStream(@"F:\new2.txt",FileMode.OpenOrCreate,FileAccess.Read))
            {
                BinaryFormatter bf = new BinaryFormatter();
                p = (Person)bf.Deserialize(fsRead);
            }
            Console.WriteLine("name:{0},age:{1},gender:{2}", p.Name, p.Age, p.Gender);
            Console.ReadKey();
        }
    }

    [Serializable]
    public class Person
    {
        private string _name;
        private int _age;
        private char _gender;

        public string Name
        {
            get
            {
                return _name;
            }

            set
            {
                _name = value;
            }
        }

        public int Age
        {
            get
            {
                return _age;
            }

            set
            {
                _age = value;
            }
        }

        public char Gender
        {
            get
            {
                return _gender;
            }

            set
            {
                _gender = value;
            }
        }
    }
}
